import 'package:flutter/foundation.dart';
import '../../models/ceramic_model.dart';
import '../services/database_service.dart';

/// 陶瓷作品删除观察者接口
abstract class CeramicDeleteObserver {
  /// 当陶瓷作品被删除时调用
  void onCeramicDeleted(int ceramicId);
}

class CeramicRepository {
  // 观察者列表
  static final List<CeramicDeleteObserver> _observers = [];

  // 添加观察者
  static void addObserver(CeramicDeleteObserver observer) {
    if (!_observers.contains(observer)) {
      _observers.add(observer);
    }
  }

  // 移除观察者
  static void removeObserver(CeramicDeleteObserver observer) {
    _observers.remove(observer);
  }

  // 通知所有观察者陶瓷作品已被删除
  static void notifyCeramicDeleted(int ceramicId) {
    for (var observer in _observers) {
      observer.onCeramicDeleted(ceramicId);
    }
  }

  final DatabaseService _databaseService = DatabaseService();

  // 表名
  final String _tableName = 'ceramics';

  // 添加陶瓷作品
  Future<int> addCeramic(Ceramic ceramic) async {
    final db = await _databaseService.database;
    return await db.insert(_tableName, ceramic.toJson());
  }

  // 更新陶瓷作品
  Future<int> updateCeramic(Ceramic ceramic) async {
    final db = await _databaseService.database;
    return await db.update(
      _tableName,
      ceramic.toJson(),
      where: 'id = ?',
      whereArgs: [ceramic.id],
    );
  }

  // 删除陶瓷作品
  Future<bool> deleteCeramic(int ceramicId) async {
    final db = await _databaseService.database;
    try {
      // 从数据库中删除陶瓷作品
      final result = await db.delete(
        _tableName,
        where: 'id = ?',
        whereArgs: [ceramicId],
      );

      // 如果删除成功，通知所有观察者
      if (result > 0) {
        notifyCeramicDeleted(ceramicId);
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('删除陶瓷作品失败: $e');
      return false;
    }
  }

  // 根据ID获取陶瓷作品
  Future<Ceramic?> getCeramicById(int id) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return Ceramic.fromJson(maps.first);
    }
    return null;
  }

  // 获取用户的所有陶瓷作品
  Future<List<Ceramic>> getUserCeramics(int userId) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'user_id = ?',
      whereArgs: [userId],
      orderBy: 'created_at DESC',
    );

    return List.generate(maps.length, (i) => Ceramic.fromJson(maps[i]));
  }

  // 获取所有陶瓷作品
  Future<List<Ceramic>> getAllCeramics() async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      orderBy: 'created_at DESC',
    );

    return List.generate(maps.length, (i) => Ceramic.fromJson(maps[i]));
  }

  // 增加点赞数
  Future<int> incrementLikeCount(int ceramicId) async {
    final db = await _databaseService.database;

    // 先获取当前点赞数
    var ceramic = await getCeramicById(ceramicId);
    if (ceramic == null) return 0;

    // 更新点赞数
    return await db.update(
      _tableName,
      {'like_count': ceramic.likeCount + 1},
      where: 'id = ?',
      whereArgs: [ceramicId],
    );
  }

  // 减少点赞数
  Future<int> decrementLikeCount(int ceramicId) async {
    final db = await _databaseService.database;

    // 先获取当前点赞数
    var ceramic = await getCeramicById(ceramicId);
    if (ceramic == null || ceramic.likeCount <= 0) return 0;

    // 更新点赞数
    return await db.update(
      _tableName,
      {'like_count': ceramic.likeCount - 1},
      where: 'id = ?',
      whereArgs: [ceramicId],
    );
  }

  // 增加收藏数
  Future<int> incrementFavoriteCount(int ceramicId) async {
    final db = await _databaseService.database;

    // 先获取当前收藏数
    var ceramic = await getCeramicById(ceramicId);
    if (ceramic == null) return 0;

    // 更新收藏数
    return await db.update(
      _tableName,
      {'favorite_count': ceramic.favoriteCount + 1},
      where: 'id = ?',
      whereArgs: [ceramicId],
    );
  }

  // 减少收藏数
  Future<int> decrementFavoriteCount(int ceramicId) async {
    final db = await _databaseService.database;

    // 先获取当前收藏数
    var ceramic = await getCeramicById(ceramicId);
    if (ceramic == null || ceramic.favoriteCount <= 0) return 0;

    // 更新收藏数
    return await db.update(
      _tableName,
      {'favorite_count': ceramic.favoriteCount - 1},
      where: 'id = ?',
      whereArgs: [ceramicId],
    );
  }

  // 搜索陶瓷作品（按标题或描述）
  Future<List<Ceramic>> searchCeramics(String keyword) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'title LIKE ? OR description LIKE ?',
      whereArgs: ['%$keyword%', '%$keyword%'],
      orderBy: 'created_at DESC',
    );

    return List.generate(maps.length, (i) => Ceramic.fromJson(maps[i]));
  }
}
